package com.happe.foodeasy.client.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.happe.foodeasy.client.CommodityClient;
import com.happe.foodeasy.dto.CommodityBaseDTO;
import com.happe.foodeasy.dto.CommodityTypeDTO;
import com.happe.foodeasy.dto.PageInfoDto;
import com.happe.foodeasy.util.ManageSystemInfoContainer;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

@Component
public class CommodityClientImpl implements CommodityClient {
    @Override
    public long selectTotalCountByParam(long commodityTypeId, long commodityStateId) {
        return 0;
    }

    @Override
    public List<CommodityBaseDTO> selectTargetCommodityByParam(long commodityTypeId, PageInfoDto pageInfoDto) {
        return null;
    }

    @Override
    public List<CommodityTypeDTO> selectAllCommodityType() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(ManageSystemInfoContainer.retrieveUrl() + "commodity/retrieveAllCommodityType.do");
        try {
           return client.execute(httpGet, commodityTypeHandler);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private ResponseHandler<List<CommodityTypeDTO>> commodityTypeHandler = new ResponseHandler<List<CommodityTypeDTO>>() {
        @Override
        public List<CommodityTypeDTO> handleResponse(HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if(statusLine.getStatusCode() > 300){
                throw new HttpResponseException(
                        statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            return JSON.parseObject(entity.getContent(),charset, new TypeReference<List<CommodityTypeDTO>>(){}.getType());
        }
    };
}
